<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/6/16
 */

namespace backend\services;

class LogService
{
    public function log($data, $type = '', $fileName = '', $cutByDt = false, $showTimestamp = true, $sep = "\t")
    {
        $now = time();
        $date = date('Y-m-d H:i:s', $now);
        $result = [$date];
        if ($showTimestamp) {
            $result[] = $now;
        }
        if (!empty($type)) {
            $result[] = $type;
        }
        foreach ($data as $item) {
            if (is_array($item) || is_object($item)) $item = json_encode($item);
            $result[] = str_replace("\t", '', $item);
        }
        $txt = implode($sep, $result) . "\n";
        $fileOutput = !empty($cutByDt) ? ($fileName . '_' . date('Y-m-d') . '.log') : ($fileName . '.log');

        $path = '../runtime/logs/';
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        $fd = fopen($path . $fileOutput, 'a+');
        fwrite($fd, $txt);
        fclose($fd);
    }
}